package sms;
import java.util.Hashtable;

import dbmanager.DBManager;

public class RecieveSMS
{
	static boolean INUSE = false;
	DBManager database;
	Modem modem;
	SMSDetails smd ;
	PortHandler handle;
	
	public RecieveSMS() 
	{
		modem = new Modem("/dev/ttyUSB0","230400");
		handle = modem.getPortHandler();
	}
	
	public PortHandler getPortHandler()
	{
		return handle;
	}
	
	void setDatabase(DBManager database)
	{
		this.database = database;
	}
	public boolean recieveSMS()
	{
		System.out.println("THIS IS RECEVIE METHOD");
		boolean flag = false;
		
		if(!INUSE)
		{
			INUSE = true;
			for(int k = 0; k <= 15;)
			{
				try
				{
				    k++;
				    smd = modem.recieveSMS(k);
				    if(!smd.getError())
				    	continue;
				    Hashtable<Object, Object> insertHash = new Hashtable<Object, Object>();
				    
				    insertHash.put("Mobile", smd.getNumber());
				    String sms = smd.getData();
				    if(sms.length()-1 == 153)
				    {
				    	insertHash.put("multiple","1");
				    }
					insertHash.put("Message",sms);
					insertHash.put("datetime", smd.getDate());
					System.out.println("Incoming Message Details are "+ insertHash);
				    
				    database.getInsert("SMS", insertHash);
				    flag = true;
				}
			    catch(Exception e)
			    {
			        e.printStackTrace();
			        k++;
			    }
			}
			INUSE = false;
		}
		return flag;
	 }
	
	public static void main(String[] args) 
	{
		RecieveSMS recieve = new RecieveSMS();
		DBManager db = new DBManager();
		db.getConnect();
		recieve.setDatabase(db);
		recieve.recieveSMS();
		
	}
}